﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Net;
using System.IO;

namespace Gekko.Libraries
{
	[XmlRoot("Gekko")]
	public class VersionCheck
	{
		string v_version = "0.0.1.1";
		DateTime v_release = new DateTime();
		string v_comment = string.Empty;
		string v_path = string.Empty;
		string v_filepath = string.Empty;
		Exception v_ex = null;

		/// <summary>
		/// ダウンロードできるバージョン
		/// </summary>
		public string Version
		{
			get { return v_version; }
			set { v_version = value; }
		}

		/// <summary>
		/// リリース日時
		/// </summary>
		public DateTime ReleaseDate
		{
			get { return v_release; }
			set { v_release = value; }
		}

		/// <summary>
		/// バージョンアップ内容
		/// </summary>
		public string Comment
		{
			get { return v_comment; }
			set { v_comment = value; }
		}

		/// <summary>
		/// ダウンロードパス
		/// </summary>
		public string Path
		{
			get { return v_path; }
			set { v_path = value; }
		}

		/// <summary>
		/// ファイル名
		/// </summary>
		public string FileName
		{
			get { return v_filepath; }
			set { v_filepath = value; }
		}

		/// <summary>
		/// 通信にエラーがあったか
		/// </summary>
		[XmlIgnore()]
		public Exception Exception
		{
			get { return v_ex; }
			set { v_ex = value; }
		}
	}

#region 処理
	public class VersionChecker
	{
		VersionCheck vc = new VersionCheck();
		const string CHECK_URI = "http://soft.udonge.net/Gekko.xml";

		public VersionCheck Check()
		{
			// メール取得準備
			try
			{
				HttpWebRequest hwreq = (HttpWebRequest)HttpWebRequest.Create(CHECK_URI);
				// プロキシ
				if (ReadSetting.Setting.UseProxy)
				{
					if (ReadSetting.Setting.UseIeProxy)
						hwreq.Proxy = WebRequest.GetSystemWebProxy();
					else
						hwreq.Proxy = new WebProxy(ReadSetting.Setting.ProxyHostName, ReadSetting.Setting.ProxyPort);
				}
				else
				{
					hwreq.Proxy = null;
				}
				hwreq.Method = "GET";

				// 取得開始
				using (HttpWebResponse hwres = (HttpWebResponse)hwreq.GetResponse())
				using (StreamReader sr = new StreamReader(hwres.GetResponseStream()))
				{
					XmlSerializer xs = new XmlSerializer(typeof(VersionCheck));
					try
					{
						vc = (VersionCheck)xs.Deserialize(sr);
						vc.Exception = null;
						return vc;
					}
					catch (InvalidOperationException ex)
					{
						vc.Exception = ex;
						return vc;
					}
				}
			}
			catch (WebException ex)
			{
				vc.Exception = ex;
				return vc;

			}
		}

	}
#endregion
}
